<?php

/**
 * Name: 员工仓库层
 * User: Silent
 * Date: 2025-09-20
 * Time: 22:45:54
 */

namespace App\Repositories\Config;

use App\Models\Config\Employee;
use App\Models\Message\Message;
use App\Models\Message\UserMessage;
use App\Models\Safety\ProductionAccident;
use App\Models\Safety\Question;
use App\Models\Safety\RiskSource;
use App\Models\Safety\SafetyHazard;
use App\Models\Checkin\SignInRecord;
use App\Models\Checkin\LeaderReview;
use App\Models\Checkin\DutyLeader;
use App\Models\Checkin\DutySupervisor;
use App\Repositories\BaseRepository;
use Carbon\Carbon;

class EmployeeRepository extends BaseRepository
{
    public function __construct(Employee $model)
    {
        parent::__construct($model);
    }

    /**
     * 根据userid查询员工.
     *
     * @param int $userid
     */
    public function findByUseridWithEmployee(int $userid)
    {
        return $this->model->where('wechat_user_id', $userid)->first();
    }

    /**
     * 根据用户ID获取用户信息
     *
     * @param int|null $userId
     * @param string|null $date 查询日期，格式：Y-m-d，默认今天
     * @return array
     */
    public function getUserInfoById(?int $userId, ?string $date = null)
    {
        // 如果用户ID为空，返回空数据结构
        if (!$userId) {
            return [
                'info' => null,
                'count' => [
                    'riskCount' => 0,
                    'accidentCount' => 0,
                    'questionCount' => 0,
                    'hazardCount' => 0,
                    'thisMonthCheckIn' => 0,
                    'totalCheckIn' => 0,
                ],
                'unreadCount' => 0,
            ];
        }

        $info = $this->model->where('id', $userId)
            ->with('wechatUser')
            ->first();

        // 获取本月开始和结束时间
        $thisMonthStart = Carbon::now()->startOfMonth();
        $thisMonthEnd = Carbon::now()->endOfMonth();

        // 统计签到数据
        $thisMonthCheckIn = app(SignInRecord::class)
            ->where('employee_id', $userId)
            ->whereBetween('sign_date', [$thisMonthStart, $thisMonthEnd])
            ->whereNull('deleted_at')
            ->count();

        $totalCheckIn = app(SignInRecord::class)
            ->where('employee_id', $userId)
            ->whereNull('deleted_at')
            ->count();

        $count = [
            'riskCount'        => app(RiskSource::class)->where('employees_id', $userId)->get()->count(),
            'accidentCount'    => app(ProductionAccident::class)->where('employees_id', $userId)->get()->count(),
            'questionCount'    => app(Question::class)->where('employees_id', $userId)->get()->count(),
            'hazardCount'      => app(SafetyHazard::class)->where('employees_id', $userId)->get()->count(),
            'thisMonthCheckIn' => $thisMonthCheckIn, // 本月打卡数
            'totalCheckIn'     => $totalCheckIn,     // 累计打卡数
        ];

        // 如果是主管/部长/副部长，添加班组统计数据
        if ($info && in_array($info->position, ['主管', '部长', '副部长'])) {
            $queryDate = $date ?: Carbon::today()->format('Y-m-d');
            
            // 今日班组：统计指定日期有签到记录的班组数量
            $todayTeamsCount = app(SignInRecord::class)
                ->where('sign_date', $queryDate)
                ->whereNull('deleted_at')
                ->distinct()
                ->count('team_name');
            
            // 异常班组：统计指定日期班长审核状态为异常的班组数
            $abnormalTeamsCount = app(LeaderReview::class)
                ->where('review_date', $queryDate)
                ->where('review_status', 'rejected')
                ->whereNull('deleted_at')
                ->count();
            
            // 管理人数：统计指定日期签到的总人数
            $managedEmployeesCount = app(SignInRecord::class)
                ->where('sign_date', $queryDate)
                ->whereNull('deleted_at')
                ->distinct()
                ->count('employee_id');
            
            $count['todayTeamsCount'] = $todayTeamsCount;           // 今日班组数
            $count['abnormalTeamsCount'] = $abnormalTeamsCount;     // 异常班组数
            $count['managedEmployeesCount'] = $managedEmployeesCount; // 管理人数
        }

        // 查询当天的值班班长信息（可能有多个班组）
        $queryDate = $date ?: Carbon::today()->format('Y-m-d');
        $dutyLeaders = DutyLeader::where('duty_date', $queryDate)
            ->with('leader')
            ->get()
            ->map(function ($dutyLeader) {
                return [
                    'id' => $dutyLeader->id,
                    'leader_id' => $dutyLeader->leader_id,
                    'leader_name' => $dutyLeader->leader_name,
                    'team_name' => $dutyLeader->team_name,
                    'duty_date' => $dutyLeader->duty_date,
                ];
            });

        // 查询当天的值班领导信息
        $dutySupervisor = DutySupervisor::where('duty_date', $queryDate)
            ->with('supervisor')
            ->first();
        
        $dutySupervisorData = null;
        if ($dutySupervisor) {
            $dutySupervisorData = [
                'id' => $dutySupervisor->id,
                'supervisor_id' => $dutySupervisor->supervisor_id,
                'supervisor_name' => $dutySupervisor->supervisor_name,
                'phone' => $dutySupervisor->phone,
                'location' => $dutySupervisor->location,
                'time_range' => $dutySupervisor->time_range,
                'remark' => $dutySupervisor->remark,
                'duty_date' => $dutySupervisor->duty_date,
            ];
        }

        return [
            'info'  => $info,
            'count' => $count,
            'unreadCount' => app(UserMessage::class)->where('employees_id', $userId)->where('status', 0)->get()->count(),
            'dutyLeaders' => $dutyLeaders,
            'dutySupervisor' => $dutySupervisorData,
        ];
    }
}
